package com.apes.framework.plugin.esb.processor.connector.oap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.esb.processor.AbstractChainProcessor;
import com.apes.oap.RopRequestContext;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * 功能：
 *
 * @author xul
 * @create 2019-11-08 10:33
 */
public class OapResponseProcessor<T extends SimpleRequest, R> extends AbstractChainProcessor<T, R> {

    @Override
   protected R doProcess(T data) {
        JSONObject jo = data.getJO();
        JSONObject header = jo.getJSONObject("header");
        if (header == null) throw new RuntimeException("数据格式错误！");
        String code = header.getString("code");
        code = code != null ? code : "success";
        if (!code.equals("success")) {
            RopRequestContext context  = data.getRopRequestContext();
            HttpServletResponse response = (HttpServletResponse) context.getRawResponseObject();
            if(response == null)  throw new RuntimeException(header.getString("message"));
            response.setContentType("application/json;charset=utf-8");
            try (OutputStream os = response.getOutputStream()) {
                os.write((jo.toJSONString()).getBytes());
                os.flush();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            throw new RuntimeException(jo.toJSONString());
        }
        if (!jo.containsKey("body")) return null;
        return (R) jo.get("body");
    }
}
